#include "preHeader.h"
#include "IMapHook.h"
#include "MapInstance.h"

IMapHook::IMapHook(MapInstance* pMapInstance)
: m_pMapInstance(pMapInstance)
{
}

IMapHook::~IMapHook()
{
}

WheelTimerMgr *IMapHook::GetWheelTimerMgr()
{
	return &m_pMapInstance->sWheelTimerMgr;
}

void IMapHook::InitLuaEnv()
{
	auto L = m_pMapInstance->L;
	lua::class_add<IMapHook>(L, "IMapHook");
	lua::class_def<IMapHook>(L, "GetMapInstance", &IMapHook::GetMapInstance);
	lua::class_def<IMapHook>(L, "GetVariables", &IMapHook::GetVariables);
	lua::class_def<IMapHook>(L, "WatchShutdownMapInstance", &IMapHook::WatchShutdownMapInstance);
	lua::class_def<IMapHook>(L, "ShutdownMapInstance", &IMapHook::ShutdownMapInstance);

	lua_newtable(L);
	m_variables = LuaRef(L, true);

	char buffer[PATH_MAX];
	snprintf(buffer, sizeof(buffer),
		"scripts/Map/Hook/%d.lua", 1000 + m_pMapInstance->getMapType());
	if (OS::is_file_exist(buffer)) {
		RunScriptFile(m_pMapInstance->L, buffer, m_pMapInstance, this);
	}
}

void IMapHook::OnMapInstanceStart()
{
}

void IMapHook::Update(uint64 diffTime)
{
}

vector3f1f IMapHook::GetEntryPoint(
	uint32 gsIdx, const CharTeleportInfo& tpInfo) const
{
	return {tpInfo.x, tpInfo.y, tpInfo.z, tpInfo.o};
}

void IMapHook::WatchShutdownMapInstance(uint32 tickMS, uint32 delayMS)
{
	RemoveTimers(TimerTypeTryShutdownInstance);
	RemoveTimers(TimerTypeWatchShutdownInstance);
	CreateTimer([=]() {
		if (m_pMapInstance->GetMostPossiblePlayerCount() == 0) {
			if (!HasTimer(TimerTypeTryShutdownInstance)) {
				CreateTimer([=]() {
					m_pMapInstance->Shutdown();
				}, TimerTypeTryShutdownInstance, delayMS, 1);
			}
		} else {
			RemoveTimers(TimerTypeTryShutdownInstance);
		}
	}, TimerTypeWatchShutdownInstance, tickMS, 0);
}

void IMapHook::ShutdownMapInstance(uint32 delayMS)
{
	RemoveTimers(TimerTypeTryShutdownInstance);
	RemoveTimers(TimerTypeWatchShutdownInstance);
	CreateTimerX([=]() {
		m_pMapInstance->Shutdown();
	}, delayMS, 1);
}
